package org.example.likou150.tree;

// https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/description/?envType=study-plan-v2&envId=top-interview-150
public class Connect {

    public static void main(String[] args) {
        // 构建上面的二叉树
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.right = new Node(7);

        // 你的 connect 方法
        Connect connect = new Connect();
        connect.connect(root);
    }

    public Node connect(Node root) {
        Node pre = root;
        Node head = new Node(0);
        Node n = head;
        while (pre!=null){
            n.next = null;
            if(pre.left!=null) {
                n.next = pre.left;
                n = n.next;
            }
            if(pre.right!=null){
                n.next = pre.right;
                n = n.next;
            }
            pre = pre.next;
        }
        if(head.next!=null){
            connect(head.next);
        }
        return root;
    }


    private static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };
}
